﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;

using BusinessFacade;
using EntityManage;


public partial class Modules_Personal_EvaluateList : System.Web.UI.Page
{

    IPerf_Personal_EvaluateHandler evaluateHandler = new Perf_Personal_EvaluateManage();
    IPerf_Personal_EvaluateDtlHandler evaluateDtlHandler = new Perf_Personal_EvaluateDtlManage();

    ISys_OrganizationHandler organizationHandler = new Sys_OrganizationManage();

    IPerf_Personal_TargetOwnerHandler targetOwnerHandler = new Perf_Personal_TargetOwnerManage();
    DataBase db = new DataBase();

    ISys_UserHandlerExt userHandlerExt = new Sys_UserManageExt();
    IPerf_Personal_EvaluateHandlerExt evaluateHandlerExt = new Perf_Personal_EvaluateManageExt();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Id";
            ViewState["Accending"] = "desc";
            FillDll();
            dataBind();

        }

    }
 
    private void FillDll()
    {
        DataTable dt = targetOwnerHandler.GetPerf_Personal_TargetOwnerList();
        ddlTargetOwner.DataTextField = "Name";
        ddlTargetOwner.DataValueField = "ID";
        ddlTargetOwner.DataSource = dt;
        ddlTargetOwner.DataBind();
        ddlTargetOwner.Items.Insert(0, new ListItem("全部....", "0"));
    }
 
    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("303010"))
            {
                if (strPur.Contains("303011"))
                {
                    btnCreate.Visible = true;
                }
                else
                {
                    btnCreate.Visible = false;
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 根据ID获取用户名称
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public string GetUserName(object id)
    {
        return userHandlerExt.GetUserNameByID(int.Parse(id.ToString()));
    }

/// <summary>
/// 根据评分ID获取评分人
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
    public string GetUserNameByEvaluateID(object id)
    {
        string names=string.Empty;
        Perf_Personal_EvaluateDtlQuery[] evaluateDtl = evaluateDtlHandler.GetPerf_Personal_EvaluateDtlQueryList("Evaluate_ID=@Evaluate_ID", new SqlParameter[] { new SqlParameter("@Evaluate_ID",id.ToString())});
        if (evaluateDtl != null && evaluateDtl.Length > 0)
        {
            foreach (Perf_Personal_EvaluateDtlQuery q in evaluateDtl)
            {
                string name = userHandlerExt.GetUserNameByID(q.User_ID);
               if (!names.Contains(name))
               {
                   names += name+",";
               }

            }
        }
        return names.TrimEnd(new char[] { ',' });
    }

    public string GetTargetOwner(object id)
    { 
        string name=string.Empty;
        Perf_Personal_TargetOwnerQuery query = targetOwnerHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(id.ToString()));
        if (query != null)
        {
            name = query.Name;
        }
        return name;
    }

    public string GetTotalScore(object id)
    {
        string score = string.Empty;
        score = evaluateHandlerExt.GetTotalScore(int.Parse(id.ToString())).ToString("0.00");
        return score;
    }

    protected void btnCreate_Click(object sender, EventArgs e)
    {
        dataBind();
    }

    /// <summary>
    /// 初始绩效评分信息表
    /// </summary>
    private void dataBind()
    {
        try
        {
            //当前用户所属部门(如果当前用户有借调部门就优先借调部门)
            int currUserOrgID = 0;
            if (Session["OrgID2"] != null)
            {
                if (Session["OrgID2"].ToString() != string.Empty && Session["OrgID2"].ToString() != "0")
                {
                    currUserOrgID = int.Parse(Session["OrgID2"].ToString());
                }
                else if (Session["OrgID"] != null)
                {
                    currUserOrgID = int.Parse(Session["OrgID"].ToString());
                }               
            }

            Sys_OrganizationQuery orgQuery = organizationHandler.GetSys_OrganizationQuery(currUserOrgID);
            if (orgQuery != null)
            {

                //获取父部门
                Sys_OrganizationQuery orgPQuery = organizationHandler.GetSys_OrganizationQuery(orgQuery.Parent_ID);

                if (orgPQuery != null)
                {
                    //根据父部门ID获取所有子部门ID
                    string subOrgID = string.Empty;
                    string sqlSub = @"select ID from Sys_Organization where Parent_ID=" + orgPQuery.ID;
                    DataTable dtSub = db.RunSql(sqlSub);
                    if (dtSub != null && dtSub.Rows.Count > 0)
                    {
                        foreach (DataRow r in dtSub.Rows)
                        {
                            subOrgID += r["ID"].ToString() + ",";
                        }

                        //当前用户是属于工商所或机关才有评分
                        if (orgQuery.Type.ToString() == Enums.OrgType.Office.ToString("d") || (orgQuery.Type.ToString() == Enums.OrgType.ICU.ToString("d"))
                            || orgPQuery.Type.ToString() == Enums.OrgType.Office.ToString("d") || (orgPQuery.Type.ToString() == Enums.OrgType.ICU.ToString("d")))
                        {

                            string sqlStr = @"select pe.*,(case when u.Org_ID2>0 then Org_ID2 else u.Org_ID end) as ORGID 
from Perf_Personal_Evaluate as pe inner join Sys_User u on pe.Target_User_ID=u.ID
where (case when u.Org_ID2>0 then Org_ID2 else u.Org_ID end) in(" + subOrgID.TrimEnd(new char[]{','}) + ") ";
                            DataTable dtCounter = new DataTable();
                            int counter = 0;
                            DataTable dt = new DataTable();
                            SqlParameter[] parms1 = null;
                            SqlParameter[] parms2 = null;
                            string whereClause = string.Empty;
                            string whereClause2 = string.Empty;
                            ProcessParms(ref whereClause, ref parms1);
                            ProcessParms(ref whereClause2, ref parms2);

                            if (whereClause != string.Empty)
                            {

                                dt = db.GetDataTableByIndex(sqlStr + whereClause + " order by " + ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), parms1, AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                                // whereClause = "1=1";                      
                                dtCounter = db.RunSqlTab(sqlStr + whereClause2, parms2);
                                if (dtCounter != null && dtCounter.Rows.Count > 0)
                                {
                                    counter = dtCounter.Rows.Count;
                                }
                            }
                            else
                            {
                                dt = db.GetDataTableByIndex(sqlStr + " order by " + ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                                dtCounter = db.RunSql(sqlStr);
                                if (dtCounter != null && dtCounter.Rows.Count > 0)
                                {
                                    counter = dtCounter.Rows.Count;
                                }
                            }

                            this.AspNetPager.RecordCount = counter;
                            gvEvaluateList.DataSource = dt;
                            gvEvaluateList.DataBind();
                        }
                    }
                }
            }
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();


        if (ViewState["TargetOwner"] != null)
        {
            whereClause += " and TargetOwner_ID =@TargetOwner_ID";
            lstParm.Add(new SqlParameter("@TargetOwner_ID", ViewState["TargetOwner_ID"].ToString()));
        }

        if (ViewState["Status"] != null)
        {
            whereClause += " and pe.Status =@Status";
            lstParm.Add(new SqlParameter("@Status", ViewState["Status"].ToString()));
        }

        if (ViewState["DateFrom"] != null && ViewState["DateTo"] != null)
        {
            whereClause += " and Create_Time >=@DateFrom and Create_Time <=@DateTo";
            lstParm.Add(new SqlParameter("@DateFrom",ViewState["DateFrom"].ToString()));
            lstParm.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString()));

        }
        else if (ViewState["DateFrom"] != null && ViewState["DateTo"] == null)
        {
            whereClause += " and Create_Time >=@DateFrom";
            lstParm.Add(new SqlParameter("@DateFrom", ViewState["DateFrom"].ToString()));
        }
        else if (ViewState["DateFrom"] == null && ViewState["DateTo"] != null)
        {
            whereClause += " and Create_Time >=@DateTo";
            lstParm.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString()));
        }

        parms = lstParm.ToArray();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (ddlTargetOwner.SelectedValue!="0")
            ViewState["TargetOwner_ID"] = ddlTargetOwner.SelectedValue;
        else
            ViewState["TargetOwner_ID"] = null;

        if (ddlStatus.SelectedValue !="-1")
            ViewState["Status"] = ddlStatus.SelectedValue;
        else
            ViewState["Status"] = null;

        if (txtDateFrom.Value != string.Empty)
        {
            ViewState["DateFrom"] = txtDateFrom.Value + " 00:00:00";
        }
        else
        {
            ViewState["DateFrom"] = null;
        }

        if (txtDateTo.Value != string.Empty)
        {
            ViewState["DateTo"] = txtDateTo.Value + " 23:59:59";
        }
        else
        {
            ViewState["DateTo"] = null;
        }

       
        dataBind();
    }

    protected void gvEvaluateList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "reload")
        {
            dataBind();
        }

        if (e.CommandName == "del")
        {
            try
            {
                int evaluateID = 0;
                int.TryParse(e.CommandArgument.ToString(), out evaluateID);
                evaluateDtlHandler.DeletePerf_Personal_EvaluateDtl("Evaluate_ID=@Evaluate_ID", new SqlParameter[] { new SqlParameter("@Evaluate_ID", evaluateID.ToString()) });
                evaluateHandler.DeletePerf_Personal_Evaluate(evaluateID);
                Jscript.AlertInAjax("操作成功!",UpdatePanel1);
                dataBind();
            }
            catch { Jscript.AlertInAjax("操作失败!", UpdatePanel1); }
        }
    }

    protected void gvEvaluateList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // ImageButton ibtnDel = (ImageButton)e.Row.FindControl("ibtnDelete");
            //ImageButton ibtnStep = (ImageButton)e.Row.FindControl("ibtnStep");
            //if (Session["UserPurviews"] != null)
            //{
            //    if (Session["UserPurviews"].ToString().Contains("401020"))//删除
            //    {
            //        ibtnDel.Visible = true;
            //    }
            //    else
            //    {
            //        ibtnDel.Visible = false;
            //    }
            //}

        }
    }

    protected void gvEvaluateList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }
     
        dataBind();
    }


    protected void CreateButton_Click(object sender, EventArgs e)
    {
        dataBind();
    }
    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
       
        dataBind();
    }
    
}
